package com.caiyi.financial.nirvana.sms.aspect;

import com.caiyi.financial.nirvana.sms.entity.SmsBase;
import com.caiyi.financial.nirvana.sms.querybean.BaseQueryBean;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 拦截url请求，去除参数中空格
 */
@Aspect
@Component
public class RequestUrlAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "execution(* com.caiyi.financial.nirvana.sms.controller.*.*(..))")
    public void pointCutMethod() {
    }

    @Before("pointCutMethod()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                if (args[i] == null) {
                    continue;
                }
                if (args[i] instanceof String) {
                    args[i] = args[i].toString().trim();
                    continue;
                }
                if (args[i] instanceof BaseQueryBean || args[i] instanceof SmsBase) {
                    //获取实体类型字段
                    Field[] fields = args[i].getClass().getDeclaredFields();
                    for (Field f : fields) {
                        f.setAccessible(true);
                        //如果该字段是String类型和非final类型,去除空格
                        if (f.getType() == String.class) {
                            if (f.get(args[i]) != null) {
                                f.set(args[i], f.get(args[i]).toString().trim());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("拦截参数出错", e);
        }
    }
}

